package com.sun.androidexerciseproject.function.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Iterator;

/**
 * Created by Administrator on 2017/6/16.
 */

public final class NetworkUtil {
    public static void testIp() {
        //ip
        String ipaddr = "http://pv.sohu.com/cityjson?/";
        URL infoUrl;
        InputStream inStream;
        try {
            infoUrl = new URL(ipaddr);
            URLConnection connection = infoUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            LogUtil.log("responseCode " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
                //if use utf-8 messy code instead of gb2312
                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "gb2312"));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                inStream.close();
                line = sb.toString();
                int first = line.indexOf("{");
                int end = line.lastIndexOf("}");
                if (-1 != first && -1 != end) {
                    JSONObject jsonObject = new JSONObject(line.substring(first, (end + 1)));
                    System.out.println(jsonObject.toString());
                    Iterator<String> key = jsonObject.keys();
                    while (key.hasNext()) {
                        System.out.println(key.next());
                    }
                    LogUtil.log(line);
                    JSONObject object = new JSONObject();
                    object.put("name", "zhangsan");
                    object.put("city", "tangshan");
                    object.put("sex", "male");
                    System.out.println(object.toString());
                }
                return;
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            System.out.println("MalformedURLException reason " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("IOException reason " + e.getMessage());
            e.printStackTrace();
        } catch (JSONException e) {
            System.out.println("JSONException reason " + e.getMessage());
            e.printStackTrace();
        }
        return;
    }

    public static String getIp(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            //获取wifi服务
            WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            //判断wifi是否开启
            if (!wifiManager.isWifiEnabled()) {
                wifiManager.setWifiEnabled(true);
            }
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            String ip = formatIpAddress(ipAddress);
            return ip;
        }
        if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            return getGPRSLocalIpAddress();
        }
        return null;
    }

    private static String formatIpAddress(int ipAdress) {

        return (ipAdress & 0xFF) + "." +
                ((ipAdress >> 8) & 0xFF) + "." +
                ((ipAdress >> 16) & 0xFF) + "." +
                (ipAdress >> 24 & 0xFF);
    }

    public static String getGPRSLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("WifiPreference IpAddress", ex.toString());
        }
        return null;
    }
}
